package com.zifan.sever.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zifan.sever.bean.Department;
import com.zifan.sever.mapper.DepartmentMapper;
import com.zifan.sever.service.IDepartmentService;
import com.zifan.sever.utils.RespBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zifan
 * @since 2021-04-10
 */
@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements IDepartmentService {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    /**
     * 获取所有部门，每个部门带有自己的子部门
     * @return
     */
    @Override
    public List<Department> getAllDepartment() {

        ValueOperations<String, Object> operations = redisTemplate.opsForValue();
        List<Department> depList = (List<Department>)operations.get("depList");
        if (ObjectUtil.isNotNull(depList)){
            return depList;
        }
        //这里传的这个参数是为了递归而来
        List<Department> departments = this.baseMapper.getAllDepartment(-1);
        operations.set("depList",departments);
        return departments;
        //todo (已完成) 这里递归查询这么离谱，要整个redis缓存一下
    }

    /**
     * 添加部门（调用了存储过程）
     * @return
     */
    @Override
    public RespBean addDepartment(Department department) {
        department.setEnabled(true);
        this.baseMapper.addDepartment(department);
        if (1 == department.getResult()){
            return RespBean.success("添加成功",department);
        }
        return RespBean.error("添加失败，请联系管理员");
    }

    /**
     * 删除部门（调用了存储过程）
     * @return
     */
    @Override
    public RespBean deleteDepartment(Integer id) {
        Department dep = new Department();
        dep.setId(id);
        this.baseMapper.deleteDepartment(dep);
        Integer result = dep.getResult();
        if (-2 == result){
            return RespBean.error("该部门下还有部门，删除失败！");
        }else if(-1 == result){
            return RespBean.error("该部门下还有员工，删除失败！");
        }else if (1 == result){
            return RespBean.success("删除成功！");
        }
        return RespBean.error("错误，删除失败,请联系管理员！");
    }
}
